var express = require('express');
var app = express();
var server = require('http').createServer(app);
var employees = require('./datasource/employee');
var roles = require('./datasource/role');
var rooms = require('./datasource/room');
var room_type = require('./datasource/room_type');
var users = require('./datasource/user');
var md5 = require('./tools/md5');
var bodyParser = require('body-parser');

//fileupload
var multer = require("multer");
//file
var fs = require("fs");
//短信
var validateSMS=require('./tools/sms/messageXTools');
var Queue=require('./tools/sms/messageQueue');
var Message=require('./common/Message');

//最多一次上传10个,myFile是文件域的Name
app.use(multer({
  dest: '/tmp/'
}).array('photo', 10));
app.use(bodyParser.urlencoded({
  extended: true
}));
//assets文件夹里的所有内容被NodeJS托管,托管后页面才能显示出来
app.use(express.static(__dirname + '/src'));

//网站的入口
//当在页面地址栏输入: http://localhost:9000 就会进入本函数
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/src/index.html');
})

/****************************** 登录 *******************************/
app.post('/login', function (req, res) {
  for (var i = 0; i < users.length; i++) {
    var value = users[i];
    if (value.username == req.body.username && value.password == md5(req.body.password) && value.state == 1) {
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

/****************************** 找回密码 *******************************/

/**
 * 发送短信
 */
app.post('/sendSMS',function(req,res){
  //获取号码
  let phone = req.body.phone;
  //发送短信
  let number = validateSMS(phone);
  //存入验证码队列
  Queue.list.push(new Message(phone,number,Date.now()));
  res.send('success');
})

/**
 * 短信验证码验证
 */
app.post('/validateSMS',function(req,res){
  //获取号码
  let phone = req.body.phone;
  //获取验证码
  let code =req.body.code;
  //获取新密码
  let password=req.body.password;
  //验证
  let result = Queue.match(phone,code);
  if(result) {
    //删除队列中的验证码
    Queue.remove(phone);
    //重置新密码
    for (var i = 0; i < users.length; i++) {
      var value = users[i];
      if (value.phone == phone) {
        value.password = md5(password);
        users[i] = value;
        break;
      }
    }
    res.send('success');
  }else{
    res.send('fail');
  }
})


/****************************** 客房管理 *******************************/
/**
 * 查询所有客房信息
 */
app.get('/rooms', function (req, res) {
  res.send(rooms);
})

/**
 * 查询所有客房类型
 */
app.get('/room_type', function (req, res) {
  res.send(room_type);
})

/**
 * 添加客房类型
 */
app.post('/addRoomType',function(req,res){
  let type=req.body.type;
  let price=req.body.price;
  room_type.push({
    name:type,
    price:price
  })
  res.send('success');
})

/****************************** 员工管理 *******************************/
/**
 * 查询所有员工信息
 */
app.get('/employees', function (req, res) {
  res.send(employees);
})

/**
 * 添加新员工
 */
app.post('/addEmployee', function (req, res) {
  var url = '';
  for (var f of req.files) {
    url = req.body.username + f.originalname.substring(f.originalname.lastIndexOf('.'));
    var des_file = __dirname + "/src/assets/img/" + url; //上传的目标路径
    var data = fs.readFileSync(f.path); //读取文件的原始路径
    fs.writeFile(des_file, data, function (err) {
      err && console.log(err);
    })
  }

  var a = {
    name: req.body.username,
    sex: req.body.sex,
    age: req.body.age,
    phone: req.body.phone,
    idCard: req.body.idCard,
    photo: url,
    role: req.body.role
  }
  if (req.body.id) {
    //修改
    for (var i = 0; i < employees.length; i++) {
      if (employees[i].id == req.body.id) {
          var emp=employees[i];
          a.id=emp.id;
          a.photo = a.photo || emp.photo;
          employees[i]=a;
          break;
      }
    }
  } else {
    //新增
    var last = employees[employees.length - 1]
    a.id=last.id + 1;
    employees.unshift(a)
  }
  res.send('success');
})

//删除员工
app.post('/removeEmployee', function (req, res) {
  var id = req.body.id
  if (!id) {
    res.send('fail');
    return;
  }
  for (var i = 0; i < employees.length; i++) {
    if (employees[i].id == id) {
      //删除头像照片
      fs.unlink(__dirname + '/src/assets/img/' + employees[i].photo, function (err) {
        if (err) console.error(err);
      })
      employees.splice(i, 1)
      break;
    }
  }
  res.send('success')
})


/**
 * 根据ID查询单个员工详情
 */
app.get('/queryEmployeeById', function (req, res) {
  let id = req.query.id;
  for (var i = 0; i < employees.length; i++) {
    if (employees[i].id == id) {
      res.send(employees[i]);
      return;
    }
  }
  res.send(null);
})

/****************************** 用户管理 *******************************/
/**
 * 查询所有管理员信息
 */
app.get('/users', function (req, res) {
  res.send(users);
})

/**
 * 添加新管理员
 */
app.post('/addUser', function (req, res) {
  var username = req.body.username;
  var pass = md5(req.body.password);
  if (!username || !pass) {
    res.send('fail');
    return;
  }
  var last = users[users.length - 1]; //目前最后一个用户
  var u = {
    id: last.id + 1,
    username: username,
    password: pass,
    state: 1
  }
  users.push(u);
  res.send('success');
})

/**
 * 管理员重置密码(根据ID)
 */
app.post('/resetPassword', function (req, res) {
  // 接收参数(要修改的新密码,要修改的那个用户id号)
  var id = req.body.id;
  var password = req.body.password;
  if (!id || !password) {
    res.send('fail');
    return;
  }
  for (var i = 0; i < users.length; i++) {
    var value = users[i];
    if (value.id == id) {
      value.password = md5(password);
      users[i] = value;
      break;
    }
  }
  res.send('success');
})

/**
 * 修改管理员状态(1:正常,0冻结)
 */
app.post('/changeUserState', function (req, res) {
  var state = req.body.state;
  var id = req.body.id;
  if (!state || !id) {
    res.send('fail');
    return;
  }
  for (var i = 0; i < users.length; i++) {
    var value = users[i];
    if (value.id == id) {
      value.state = state;
      users[i] = value;
      break;
    }
  }
  res.send('success');
})


/****************************** 角色管理 *******************************/
/**
 * 查询全部角色
 */
app.get('/roles', function (req, res) {
  res.send(roles);
})

/**
 * 添加新角色
 */
app.post('/addRole', function (req, res) {
  for (var i in roles) {
    if (roles[i] == req.body.roleName) {
      res.send('exist');
      return;
    }
  }
  roles.push(req.body.roleName);
  res.send('success');
})


server.listen(9000);
console.log('Server Listening 9000 success');